const db = require('../db/index')
// 处理文件的
const fs = require('fs')

// 获取所有车辆类型
exports.carlist = (req, res) => {
    let page = req.query.page * 1
    let size = req.query.size * 1
    let from = page * size
    const sql = `select * from carbrand limit ${from},${from + size}`
    db.query(sql, (err, res2) => {
        if (err) return res.cc(err)
        res.send({
            res: res2,
        })
    })
}
// 获取我的车量
exports.mycarlist = (req, res) => {
    const data = req.body
    const sql = 'select * from mycar where userId = ? and appid=?'
    db.query(sql, [data.id, data.appid], (err, res2) => {
        if (err) return res.cc(err)
        res.send({
            res: res2,
        })
    })
}

// 添加我的车辆
exports.mycarlistadd = (req, res) => {
    const data = req.body
    if (data._id) {
        const sql = `update mycar set carName=?,carType =?,carNumber=?,carVIN=?,numberType=?,carOwner=?,carPhone=?  where _id = ${data._id}`
        db.query(sql, [data.carName, data.carType, data.carNumber, data.carVIN, data.numberType, data.carOwner, data.carPhone], (err, res2) => {
            if (err) return res.cc(err)
            res.send({
                message: '修改成功'
            })
        })
    } else {
        const sql = 'insert into mycar set ?'
        db.query(sql, data, (err, res2) => {
            if (err) return res.cc(err)
            res.send({
                message: '添加成功'
            })
        })
    }


}
// 删除我的车辆
exports.mycarlistdelete = (req, res) => {
    const id = req.body.id
    const sql = `delete from mycar where _id in(${id})`
    db.query(sql, (err, res2) => {
        if (err) return res.cc(err)
        res.send({
            message: '删除成功'
        })
    })
}
// 根据用户姓名和手机号查找用户
exports.namePhoneCarList = (req, res) => {
    let data = req.body
    let userId = []
    let sqlUser = `select * from users where phone = ? or name=?  and appid=?`
    db.query(sqlUser, [data.ownerPhone, data.ownerName, data.appid], (err, res2) => {
        if (err) return res.cc(err)
        if (res2.length > 0) {
            userId = res2.map((item) => {
                return item._id
            })
            const sql = 'select * from mycar where userId in(?) and appid=?'
            db.query(sql, [userId, data.appid], (err, res3) => {
                if (err) return res.cc(err)
                res.send({
                    res: res3,
                    message: '查询成功'
                })
            })
        } else {
            res.send({
                message: '没有找到此客户的车辆',
                res: []
            })
        }

    })

}